package com.example.huangyuchen.advance.training.camp.builder;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import lombok.experimental.SuperBuilder;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author YuChen Huang
 */
@FieldDefaults(level = AccessLevel.PRIVATE)
@SuperBuilder
@Getter
public class Detail extends BaseDomain implements Serializable {

    public static final int DEFAULT_SEQUENCE = 0;

    /**
     * 收货单ID
     */
    Long orderId;

    /**
     * 生产日期
     */
    Long productionDate;

    /**
     * 保质期
     */
    Long shelfLifeDays;

    /**
     * 过期日期
     */
    Long expiryDate;

    public static DetailBuilder<?, ?> builder() {
        return new CustomerDetailBuilderImpl();
    }

    private static final class CustomerDetailBuilderImpl extends DetailBuilder<Detail, CustomerDetailBuilderImpl> {

        final DetailBuilder<Detail, CustomerDetailBuilderImpl> builder = this;

        private CustomerDetailBuilderImpl() {
        }

        @Override
        public CustomerDetailBuilderImpl expiryDate(Long expiryDate) {
            if (Objects.isNull(builder.productionDate)) {
                throw new UnsupportedOperationException("设置过期日期前请先设置生产日期！");
            }
            return super.expiryDate(expiryDate);
        }

        /**
         * <p><h2>What</h2>
         * 参数设置前校验
         * </p>
         *
         * @return Builder
         */
        @Override
        protected CustomerDetailBuilderImpl self() {
            return this;
        }


        /**
         * <p><h2>What</h2>
         * 构造器校验
         * </p>
         *
         * @return Detail对象实例
         */
        @Override
        public Detail build() {
            if (Objects.isNull(builder.orderId)) {
                throw new UnsupportedOperationException("OrderId未设置！");
            }
            if (Objects.nonNull(builder.productionDate) && Objects.nonNull(builder.shelfLifeDays)) {
                builder.expiryDate = builder.productionDate + builder.shelfLifeDays * 24 * 3600 * 1000;
            }
            return new Detail(this);
        }
    }
}